<?php

namespace open\comm\traits;


use support\exception\BusinessException;
use Tinywan\Jwt\JwtToken;

trait OpenVerifyTrait
{

    /**
     * @param $request
     * @return array
     * @throws BusinessException
     * @author ycr <Email: yuncran@126.com>
     */
    public function before($request)
    {
        $url = $request = $request->uri(); #  '/v1/open?app_id=150&app_secret=ycr';
        $str = substr($url, strrpos($url, '?') + 1); # app_id=150&app_secret=ycr
        $array_str = explode('&', $str);
        $result = array();
        foreach ($array_str as $key => $val) {
            $str_response = explode('=', $val);
            $result[$str_response[0]] = $str_response[1];
        }
        self::checkApp($result);
        return $result;
    }


    /**
     * @param array $result
     * @return string
     * @throws BusinessException
     * @author ycr <Email: yuncran@126.com>
     */
    protected function checkApp(array $result): string
    {
        if (!isset($result['app_id']) || !isset($result['app_secret'])) {
            throw new BusinessException('appId 或 appSecret 不能为空！', 400);
        }
        $app_id = Yii()->cache::get('open_app_id_' . $result['app_id']);
        $app_secret = Yii()->cache::get('open_app_secret_' . $result['app_secret']);
        if (empty($app_id) || empty($app_secret)) {
            throw new BusinessException('未找到相对性的appId 或 appSecret,请 尽快联系管理员吧！', 500);
        }
        if ($app_id !== $result['app_id'] || $app_secret !== $result['app_secret']) {
            throw new BusinessException('您的 appId 或 appSecret 不正确！');
        }
        return true;
    }


    /**
     * 生成 token
     * @param array $result
     * @return array
     * @author ycr <Email: yuncran@126.com>
     */
    protected function createJwt(array $result): array
    {
        return JwtToken::generateToken(['id' => $result['app_id']]);
    }

    /**  */
    protected function OpenVerifyToken($token)
    {
        $JwtToken = JwtToken::verify(true, $token);
        return $JwtToken;
    }
}